package com.medical.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.medical.entity.Chat;

public interface ChatMapper extends BaseMapper<Chat> {
	/**
	 * 发送消息
	 * @param chat 
	 * @return
	 */
	@Insert("insert into t_chat (fromUserId,toUserId,content,type,time,showTime) values (#{fromUserId},#{toUserId},#{content},#{type},#{time},#{showTime})")
	@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
	public Integer sendChat(Chat chat);

	@Select("select * from t_chat where (toUserId=#{toUserId} and fromUserId=#{fromUserId}) or (toUserId=#{fromUserId} and fromUserId=#{toUserId}) order by time desc ")
	public List<Map<String, Object>> getChatList(@Param("toUserId")Integer toUserId,@Param("fromUserId")Integer fromUserId);
	
	/**
	 * 获得比当前id早的聊天记录
	 * @param toUserId 接收方id
	 * @param fromUserId 发送方id
	 * @param currentId 当前id
	 * @return
	 */
	@Select("select * from t_chat where ((toUserId=#{toUserId} and fromUserId=#{fromUserId}) or (toUserId=#{fromUserId} and fromUserId=#{toUserId})) and id<#{currentId} order by time desc ")
	public List<Map<String, Object>> getEarlyChatList(@Param("toUserId")Integer toUserId,@Param("fromUserId")Integer fromUserId, @Param("currentId")Integer currentId);
	/**
	 * 获得比当前id晚的聊天记录
	 * @param toUserId 接收方id
	 * @param fromUserId 发送方id
	 * @param currentId 当前id
	 * @return
	 */
	@Select("select * from t_chat where ((toUserId=#{toUserId} and fromUserId=#{fromUserId}) or (toUserId=#{fromUserId} and fromUserId=#{toUserId})) and id>#{currentId} order by time desc ")
	public List<Map<String, Object>> getNightChatList(@Param("toUserId")Integer toUserId,@Param("fromUserId")Integer fromUserId, @Param("currentId")Integer currentId);

	@Select("select * from t_chat where ((toUserId=#{toUserId} and fromUserId=#{fromUserId}) or (toUserId=#{fromUserId} and fromUserId=#{toUserId})) and showTime='1' order by time desc limit 0,1")
	public Chat getLastShowTime(@Param("toUserId")Integer toUserId,@Param("fromUserId")Integer fromUserId);
	
	@Select("select * from t_chat where  time in (SELECT MAX(time) from t_chat where  toUserId =#{userId} or fromUserId=#{userId} GROUP BY  CONCAT(if(fromUserId>toUserId,fromUserId,toUserId),if(fromUserId<toUserId,fromUserId,toUserId)))  ORDER BY time desc LIMIT #{page},#{size}")
	public List<Chat> getByUserId(@Param("userId")int userId,@Param("page")int page,@Param("size")int size);
}
